//
//  HCoreConfig.m
//  macWorkSpace
//
//  Created by hament on 13-8-5.
//  Copyright (c) 2013年 hament. All rights reserved.
//

#import "HCoreConfig.h"
#import "HSqlManager.h"

#import "TableEnity.h"
#import "AttributeEnity.h"

@implementation HCoreConfig


static HCoreConfig * cofig=nil;

+(HCoreConfig *)shareConfig{
    @synchronized( self )
	{
        if (cofig==nil) {
            cofig=[[HCoreConfig alloc] init];
            
            
        }
    }
    return cofig;
}




-(id)init{
    self=[super init];
    
    if (self) {

        //[self createAppSuportDirectory];//在用户目录下建立一个ａｐｐ的支持目录
        
        //oc的
        self.isArc=YES;
        self.currentLagIndex=0;//默认 objc
        
        
        self.covertTostring=NO;
        
        self.currentNameSpace=@"";//命名空间默认为空字串

        //指针类型,需要添加 * 的类型
        self.poiterTypeDic=@{OC_NSString:OC_NSString,
                             OC_NSDecimal:OC_NSDecimal,
                             OC_NSNumber:OC_NSNumber,
                             OC_NSData:OC_NSData};
        
        
      
        
        /*本地化语言*/
        self.splitePathSelect=NSLocalizedString(@"Select sqlite database path", nil);
        self.splitePath=NSLocalizedString(@"Sqlite database path", nil);
        self.analysisStr=NSLocalizedString(@"Analysis", nil);
        
        self.exportConfig=NSLocalizedString(@"Export configure", nil);
        self.entityList=NSLocalizedString(@"Entity List", nil);
        self.entitySelected=NSLocalizedString(@"Selected", nil);
        self.entityTableName=NSLocalizedString(@"Entity/Table Name", nil);
        self.PropertyName=NSLocalizedString(@"Property Name", nil);
        self.SqlType=NSLocalizedString(@"Sql Type", nil);
        self.PropertyStr=NSLocalizedString(@"Property", nil);
        self.PropertyType=NSLocalizedString(@"Property Type", nil);
        self.AllCovertString=NSLocalizedString(@"AllCovertString", nil);
        
        self.exportStr=NSLocalizedString(@"Export", nil);
        self.exportTitle=NSLocalizedString(@"Export title", nil);
        self.exportfolderPath=NSLocalizedString(@"Export folder path", nil);
        self.sqliteDbWarning=NSLocalizedString(@"warning:failed to open sqlite database with the path", nil);
        self.exportfolderWarning=NSLocalizedString(@"warning:invalid export folder path", nil);

        
    }
    return self;
    
}


//判断数据库路径是否存在,且数据库是否有效
+(BOOL)isDBPathOkWithPath:(NSString*)path{
    
    BOOL isOk=NO;
    
    
    if ([path isEqualToString:@""]) {
        return NO;
    }
    
    if ([HSqlManager checksqliteDBWithPath:path]) {
        return YES;
    }

    return isOk;
}


//判断导出的路径是否为文件夹
+(BOOL)exportFloderOkWithPath:(NSString*)path{
    
    BOOL isOk=NO;
    if ([path isEqualToString:@""]) {
        return NO;
    }

    NSError * error;
    BOOL isDir;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * dbPath=[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL * url=[NSURL URLWithString:dbPath];

    //如果文件夹存在
    if (([fileManager fileExistsAtPath:[url path] isDirectory:&isDir] && isDir)==YES) {
        
        if ([fileManager isWritableFileAtPath:[url path]]) {
        
            debugLog(@"[url path]:%@ error:%@",[url path],error.description);
            return YES;
            
        } else {
        
        return NO;
            
        }
        
    }
    
    return isOk;
}




//在用户目录下建立一个ａｐｐ的支持目录
-(void)createAppSuportDirectory{

    BOOL isDir;
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *appSupportURL = [[fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
    appSupportURL=[appSupportURL URLByAppendingPathComponent:userAppSuportFolder];
    //如果文件夹不存在,或许制定的路径不是文件夹
    if (([fileManager fileExistsAtPath:appSupportURL.absoluteString isDirectory:&isDir] && isDir)==NO) {
        [fileManager createDirectoryAtURL:appSupportURL withIntermediateDirectories:YES attributes:nil error:&error];
    }

}


//根据语言类型获取class类型集合
+(NSArray*)getObjClassTypeByIndex:(NSInteger)index{

    NSArray * arr=@[];

    switch (index) {
        case 0:
            arr=OctypeArr;
            break;
        case 1:
            arr=JavatypeArr;
            break;
        case 2:
            arr=CStypeArr;
            break;
        case 3:
            arr=CpptypeArr;
            break;
        default:
            break;
    }

    return arr;
}

//生成UUID
- (NSString *)createUniqueString {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return (__bridge NSString *)string;
}


//检查是否指针类
+(BOOL)checkIsPointerType:(NSString*)typeStr{
    BOOL isyes=YES;

    if (![[HCoreConfig shareConfig].poiterTypeDic objectForKey:typeStr]) {
        isyes =NO;
    }

    return isyes;
}


#pragma mark -----------实体类的转换---------

+(NSString*)covertToAttriType:(NSString*)sqliteType {

    NSString * covertStr;
    
    //根据用户选择的语言类型来转换
    switch ([HCoreConfig shareConfig].currentLagIndex) {
        case 0: //oc
            covertStr=[HCoreConfig covertToObjcType:sqliteType];
            break;
        case 1://java
            covertStr=[HCoreConfig covertToJavaType:sqliteType];
            break;
        case 2://c#
            covertStr=[HCoreConfig covertToCSharpType:sqliteType];
            break;
        case 3://C++
            covertStr=[HCoreConfig covertToCppType:sqliteType];
            break;
        default:
            break;
    }

    return covertStr;
}


//oc 实体类的转换 
+(NSString*)covertToObjcType:(NSString*)sqliteType{

    NSString * defaultType=@"NSString";

    if ([HCoreConfig shareConfig].covertTostring==YES) {
        return defaultType;
    }
    
    if ([sqliteType isEqualToString:@""]) {
        return defaultType;
    }
    
    //先转换一次小写
     NSString * sqlilowstr=[sqliteType lowercaseString];
    
    //整数类
    if ([sqlilowstr hasPrefix:@"int"]|| [sqlilowstr hasSuffix:@"int"]) {
        return OC_NSIntget;
    }
    
    //浮点类
    if ([sqlilowstr hasPrefix:@"real"] ||[sqlilowstr hasPrefix:@"double"]) {
         return OC_double;
    }

    
    if ([sqlilowstr hasPrefix:@"float"] ) {
        return OC_float;
    }
    
    //布尔类
    if ([sqlilowstr hasPrefix:@"bool"] ) {
        return OC_BOOL;
    }

    //data类
    if ([sqlilowstr hasPrefix:@"blob"] ) {
        return OC_NSData;
    }
    
    //十进制, 数字
    if ([sqlilowstr hasPrefix:@"decimal"] ) {
        return OC_NSDecimal;
    }
    
    if ([sqlilowstr hasPrefix:@"numeric"]) {
        return OC_NSNumber;
    }
    
    
    
    return defaultType;
}

//Java 实体类的转换 
+(NSString*)covertToJavaType:(NSString*)sqliteType{
    NSString * defaultType=@"String";
    
    
    if ([HCoreConfig shareConfig].covertTostring==YES) {
        return defaultType;
    }
    
    
    if ([sqliteType isEqualToString:@""]) {
        return defaultType;
    }
    
    //先转换一次小写
    NSString * sqlilowstr=[sqliteType lowercaseString];
    
    //整数类
    if ([sqlilowstr hasPrefix:@"int"]|| [sqlilowstr hasSuffix:@"int"]) {
        return Java_Integer;
    }
    
    //浮点类
    if ([sqlilowstr hasPrefix:@"real"] ||[sqlilowstr hasPrefix:@"double"]) {
        return Java_Double;
    }
    
    
    if ([sqlilowstr hasPrefix:@"float"] ) {
        return Java_Float;
    }
    
    //布尔类
    if ([sqlilowstr hasPrefix:@"bool"] ) {
        return Java_Boolean;
    }
    
    //data类
    if ([sqlilowstr hasPrefix:@"blob"] ) {
        return Java_String;
    }
    
    //十进制, 数字
    if ([sqlilowstr hasPrefix:@"decimal"] ) {
        return Java_BigDecimal; //需要 import java.math.BigDecimal;
    }
    
    //日期
    if ([sqlilowstr hasPrefix:@"date"] ) {
        return Java_Date; //需要 import java.util.Date;
    }

    return defaultType;

}

//C# 实体类的转换 
+(NSString*)covertToCSharpType:(NSString*)sqliteType{
    NSString * defaultType=@"string";
    
    if ([HCoreConfig shareConfig].covertTostring==YES) {
        return defaultType;
    }
    
    
    if ([sqliteType isEqualToString:@""]) {
        return defaultType;
    }
    
    //先转换一次小写
    NSString * sqlilowstr=[sqliteType lowercaseString];
    
    //整数类
    if ([sqlilowstr hasPrefix:@"int"]|| [sqlilowstr hasSuffix:@"int"]) {
        return CS_int;
    }
    
    //浮点类
    if ([sqlilowstr hasPrefix:@"real"] ||[sqlilowstr hasPrefix:@"double"]) {
        return CS_double;
    }
    
    
    if ([sqlilowstr hasPrefix:@"float"] ) {
        return CS_float;
    }
    
    //布尔类
    if ([sqlilowstr hasPrefix:@"bool"] ) {
        return CS_bool;
    }
    
    //data类
    if ([sqlilowstr hasPrefix:@"blob"] ) {
        return CS_ByteData;
    }
    
    //十进制, 数字
    if ([sqlilowstr hasPrefix:@"decimal"] ) {
        return CS_decimal; // 
    }
    
    //日期
    if ([sqlilowstr hasPrefix:@"date"] ) {
        return CS_DateTime; // 
    }
    
    return defaultType;

}

//C++ 实体类的转换 
+(NSString*)covertToCppType:(NSString*)sqliteType{

    NSString * defaultType=@"string";
    
    if ([HCoreConfig shareConfig].covertTostring==YES) {
        return defaultType;
    }
    
    
    //先转换一次小写
    NSString * sqlilowstr=[sqliteType lowercaseString];
    
    //整数类
    if ([sqlilowstr hasPrefix:@"int"]|| [sqlilowstr hasSuffix:@"int"]) {
        return CPP_int;
    }
    
    //浮点类
    if ([sqlilowstr hasPrefix:@"real"] ||[sqlilowstr hasPrefix:@"double"]) {
        return CPP_double;
    }

    if ([sqlilowstr hasPrefix:@"float"] ) {
        return CPP_float;
    }

    //布尔类
    if ([sqlilowstr hasPrefix:@"bool"] ) {
        return CPP_bool;
    }
    
    //data类
//    if ([sqlilowstr hasPrefix:@"blob"] ) {
//        return OC_NSData;
//    }
//    
    //十进制, 数字
//    if ([sqlilowstr hasPrefix:@"decimal"] ) {
//        return OC_NSDecimal;
//    }
//    
//    if ([sqlilowstr hasPrefix:@"numeric"]) {
//        return OC_NSNumber;
//    }
//    
    return defaultType;
}


#pragma mark -----------实体类的导出---------
//导出
+(void)exportToOcClass:(NSArray*)datasource folderPath:(NSString*)path{


    
    
    //转换时间
    NSDate * date =[NSDate date];
    NSDateFormatter * dateFormater=[[NSDateFormatter alloc] init];
    [dateFormater setDateStyle:NSDateFormatterShortStyle];
    NSString * dateStr=[dateFormater stringFromDate:date];
    

    
    for (TableEnity * tbenity in datasource) {
        
        
        if (tbenity.isSelected==NO) {
            continue;
        }
        
        //准备模板
        NSMutableString *templateH =[[NSMutableString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"enityT" ofType:@"oc1"]
                                                                           encoding:NSUTF8StringEncoding error:nil];
        
        NSMutableString *templateM =[[NSMutableString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"enityT" ofType:@"oc2"]
                                                                           encoding:NSUTF8StringEncoding error:nil];
        
        //属性
        NSString *proterty = @"";
        
        //dealloc str 用于arc
        NSString * deallocStr = @"";
        
        //实体类的名字
        NSString * enityName=tbenity.enityName;
        
        
        NSArray * attriarr=tbenity.attributes;
        
        for (AttributeEnity * attri in attriarr) {
            
            NSString * attributeName=attri.attributeName;//属性名字
            NSString * covertType=attri.objcType;//属性的数据类型
            
            NSString * attriFormatstr=@"";
            if ([HCoreConfig checkIsPointerType:covertType]) {
                
                attriFormatstr=[NSString stringWithFormat:@"@property (nonatomic,strong) %@ * %@ ;\n",covertType,attributeName];
                
                deallocStr =[deallocStr stringByAppendingFormat:@"[_%@ release]; \n",attributeName];
            } else {
             attriFormatstr=[NSString stringWithFormat:@"@property (nonatomic) %@  %@ ;\n",covertType,attributeName];
            }
            
            //制造属性
            proterty=[proterty stringByAppendingString:attriFormatstr];
            
            
        }


        /*---替换.h-----*/
        // 实体类名
        [templateH replaceOccurrencesOfString:ocEnityName
                                   withString:enityName
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateH.length)];
        
        // 时间
        [templateH replaceOccurrencesOfString:ocDate
                                   withString:dateStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateH.length)];
        
        // property
        [templateH replaceOccurrencesOfString:ocProperty
                                   withString:proterty
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateH.length)];
        
        
        
        
        /*---替换.m-----*/
        [templateM replaceOccurrencesOfString:ocEnityName
                                   withString:enityName
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateM.length)];
        
        [templateM replaceOccurrencesOfString:ocDate
                                   withString:dateStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateM.length)];
        
        
        //如果是arc的
        if ([HCoreConfig shareConfig].isArc) {
            [templateM replaceOccurrencesOfString:ocDealloc
                                       withString:@""
                                          options:NSCaseInsensitiveSearch
                                            range:NSMakeRange(0, templateM.length)];
        } else {
            //加上 [super dealloc]
            deallocStr=[deallocStr stringByAppendingString:@"[super dealloc];"];
            [templateM replaceOccurrencesOfString:ocDealloc
                                       withString:deallocStr
                                          options:NSCaseInsensitiveSearch
                                            range:NSMakeRange(0, templateM.length)];
        
        }
        
        
        
        
        NSString * hfileName =[NSString stringWithFormat:@"%@.h",enityName];
        NSString * mfileName =[NSString stringWithFormat:@"%@.m",enityName];
        
        //导出文件
        
        NSError * error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        /***导出.h***/
         NSString * filepath=[path stringByAppendingPathComponent:hfileName];
         filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         NSURL * url=[NSURL URLWithString:filepath];

        //如果文件存在
        if ([fileManager fileExistsAtPath:[url path]] ) {
            [fileManager removeItemAtPath:[url path] error:&error];
  
        }
        
        [templateH writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];

         /***导出.m***/
         filepath=[path stringByAppendingPathComponent:mfileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         url=[NSURL URLWithString:filepath];
        
        
        //如果文件夹存在
        if ([fileManager fileExistsAtPath:[url path]] ) {
            [fileManager removeItemAtPath:[url path] error:&error];
            
        }
        
//        [templateM writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];
        [templateM writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];
        
        debugLog(@"url: \n :%@ error:%@",[url path],error.description);

    }
    

}


//导出java
+(void)exportToJavaClass:(NSArray*)datasource folderPath:(NSString*)path{
    
    
    //package com.testAndroid.testandroid;
    //命名空间或包名
    NSString * namespace=[[HCoreConfig shareConfig].currentNameSpace stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!namespace) {
        namespace=@"";
    } else {
        namespace=[NSString stringWithFormat:@"package %@;\n",namespace];
    
    }
    
    //转换时间
    NSDate * date =[NSDate date];
    NSDateFormatter * dateFormater=[[NSDateFormatter alloc] init];
    [dateFormater setDateStyle:NSDateFormatterShortStyle];
    
    NSString * dateStr=[dateFormater stringFromDate:date];
    
//    [dateFormater setAMSymbol:@"AM"];
//    [dateFormater setPMSymbol:@"PM"];
    [dateFormater  setDateFormat:@"hh:mm"];
    NSString * timeStr=[dateFormater stringFromDate:date];//时分
    
    
    
    for (TableEnity * tbenity in datasource) {
        
        
        if (tbenity.isSelected==NO) {
            continue;
        }
        
        //准备模板
        NSMutableString *templateJava =[[NSMutableString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"enityJavaT" ofType:@"javaT"] encoding:NSUTF8StringEncoding error:nil];

        
        //importstring
        NSString *importstring = @"";
        
        
        //属性
        NSString *proterty = @"";
        BOOL hsaBigdecimal=NO;
        BOOL hasDate=NO;
        
        
        
        
        //setter and getter
         NSString * setGetterStr = @"";

        
        
        //实体类的名字
        NSString * enityName=[tbenity.enityName capitalizedString];
        
        
        NSArray * attriarr=tbenity.attributes;
        
        
        
        
        for (AttributeEnity * attri in attriarr) {
            
            NSString * attributeName=attri.attributeName;//属性名字
            NSString * covertType=attri.objcType;//属性的数据类型
            
            //变量声明
            NSString * attriFormatstr=[NSString stringWithFormat:@"public %@  %@ ;\n",covertType,attributeName];
            
            //setter
            NSString * lowPropertyName=[attributeName lowercaseString];
            NSString * capitalPropertyName=[attributeName capitalizedString];
            
            NSString * setStr=[NSString stringWithFormat:@"public void set%@(%@ %@) { \n this.%@ = %@; \n}\n \n",capitalPropertyName,covertType,lowPropertyName,attributeName,lowPropertyName];
            
            //getter
            NSString * getStr=[NSString stringWithFormat:@"public %@ get%@() { \n return %@; \n}\n \n",covertType,capitalPropertyName,attributeName];
            
            
            //制造属性
            proterty=[proterty stringByAppendingString:attriFormatstr];
            setGetterStr=[setGetterStr stringByAppendingFormat:@"//%@ \n",attributeName];
            setGetterStr=[setGetterStr stringByAppendingString:setStr];
            setGetterStr=[setGetterStr stringByAppendingString:getStr];
            
            
            //如果含有十进制的话
            if ([covertType isEqualToString:Java_BigDecimal]) {
                hsaBigdecimal=YES;
            }
            
            
            //如果有日期的话
            if ([covertType isEqualToString:Java_Date]) {
                hasDate=YES;
            }
        }
        
        
        /*---替换.java-----*/
        
        
        if (hsaBigdecimal) {
            importstring=[importstring stringByAppendingString:@"import java.math.BigDecimal;\n"];
        }
        
        if (hasDate) {
            importstring=[importstring stringByAppendingString:@"import java.util.Date;\n"];
        }
        
        //namespace
        [templateJava replaceOccurrencesOfString:NameSpaceStr
                                      withString:namespace
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateJava.length)];
        
        
        // import
        [templateJava replaceOccurrencesOfString:ImportString
                                      withString:importstring
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateJava.length)];
        
        // 实体类名
        [templateJava replaceOccurrencesOfString:ocEnityName
                                   withString:enityName
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateJava.length)];
        
        // 时间
        [templateJava replaceOccurrencesOfString:ocDate
                                   withString:dateStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateJava.length)];
        
        [templateJava replaceOccurrencesOfString:TimeStr
                                   withString:timeStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateJava.length)];
        
        // property
        [templateJava replaceOccurrencesOfString:VariableDeclare
                                   withString:proterty
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateJava.length)];
        
        
        
        
        /*---setter getter-----*/
        [templateJava replaceOccurrencesOfString:SetGetterMethod
                                   withString:setGetterStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateJava.length)];
        

        
        
        //如果是arc的

        
        NSString * javafileName =[NSString stringWithFormat:@"%@.java",enityName];

        
        //导出文件
        
        NSError * error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        /***导出.java***/
        NSString * filepath=[path stringByAppendingPathComponent:javafileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * url=[NSURL URLWithString:filepath];
        
        //如果文件夹存在
        if ([fileManager fileExistsAtPath:[url path]] ) {
            [fileManager removeItemAtPath:[url path] error:&error];
            
        }
        
        [templateJava writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];
        

        debugLog(@"url: \n :%@ error:%@",[url path],error.description);
        
    }
    
    
    
}


//c#
+(void)exportToCSharpClass:(NSArray*)datasource folderPath:(NSString*)path{

    //转换时间
    NSDate * date =[NSDate date];
    NSDateFormatter * dateFormater=[[NSDateFormatter alloc] init];
    [dateFormater setDateStyle:NSDateFormatterShortStyle];
    
    NSString * dateStr=[dateFormater stringFromDate:date];
    
    [dateFormater  setDateFormat:@"hh:mm"];
    NSString * timeStr=[dateFormater stringFromDate:date];//时分
 
    
    //命名空间或包名
    NSString * namespace=[[HCoreConfig shareConfig].currentNameSpace stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!namespace) {
        namespace=@"NameSpace";
    } 
    
    
    for (TableEnity * tbenity in datasource) {
        
        
        if (tbenity.isSelected==NO) {
            continue;
        }
        
        //准备模板
        NSMutableString *templateCS =[[NSMutableString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"enityCST" ofType:@"csT"] encoding:NSUTF8StringEncoding error:nil];

        //属性
        NSString *proterty = @"";

        //实体类的名字
        NSString * enityName=tbenity.enityName ;
        
        
        NSArray * attriarr=tbenity.attributes;

        for (AttributeEnity * attri in attriarr) {
            
            NSString * attributeName=attri.attributeName;//属性名字
            NSString * covertType=attri.objcType;//属性的数据类型
            
            //变量声明
            NSString * attriFormatstr=[NSString stringWithFormat:@"public %@ %@ { get; set; }\n",covertType,attributeName];

            //制造属性
            proterty=[proterty stringByAppendingString:attriFormatstr];

        }
        
        
        /*---替换.cs----*/
        
        // nameSpace
        [templateCS replaceOccurrencesOfString:NameSpaceStr
                                      withString:namespace
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateCS.length)];
        
        // 实体类名
        [templateCS replaceOccurrencesOfString:ocEnityName
                                      withString:enityName
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateCS.length)];
        
        // 时间
        [templateCS replaceOccurrencesOfString:ocDate
                                      withString:dateStr
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateCS.length)];
        
        [templateCS replaceOccurrencesOfString:TimeStr
                                      withString:timeStr
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateCS.length)];
        
        // property
        [templateCS replaceOccurrencesOfString:ocProperty
                                      withString:proterty
                                         options:NSCaseInsensitiveSearch
                                           range:NSMakeRange(0, templateCS.length)];
        

        NSString * csfileName =[NSString stringWithFormat:@"%@.cs",enityName];
        
        
        //导出文件
        
        NSError * error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        /***导出.cs***/
        NSString * filepath=[path stringByAppendingPathComponent:csfileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * url=[NSURL URLWithString:filepath];
        
        //如果文件夹存在
        if ([fileManager fileExistsAtPath:[url path]] ) {
            [fileManager removeItemAtPath:[url path] error:&error];
            
        }
        
        [templateCS writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];
        
        
        debugLog(@"url: \n :%@ error:%@",[url path],error.description);
        
    }
    
    
    
}


+(void)exportToCppClass:(NSArray*)datasource folderPath:(NSString*)path{

    
    //转换时间
    NSDate * date =[NSDate date];
    NSDateFormatter * dateFormater=[[NSDateFormatter alloc] init];
    [dateFormater setDateStyle:NSDateFormatterShortStyle];
    NSString * dateStr=[dateFormater stringFromDate:date];
    
    
    
    for (TableEnity * tbenity in datasource) {
        
        
        if (tbenity.isSelected==NO) {
            continue;
        }
        
        //准备模板 .h
        NSMutableString *templateH =[[NSMutableString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"enitycppT" ofType:@"cpp1"]
                                                                           encoding:NSUTF8StringEncoding error:nil];
        //.cpp
        NSMutableString *templateM =[[NSMutableString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"enitycppT" ofType:@"cpp2"]
                                                                           encoding:NSUTF8StringEncoding error:nil];
        
        //属性
        NSString *proterty = @"";
        
        
        //实体类的名字
        NSString * enityName=tbenity.enityName;
        
        
        NSArray * attriarr=tbenity.attributes;
        
        for (AttributeEnity * attri in attriarr) {
            
            NSString * attributeName=attri.attributeName;//属性名字
            NSString * covertType=attri.objcType;//属性的数据类型
            
            NSString * attriFormatstr=@"";
            

            attriFormatstr=[NSString stringWithFormat:@"  %@ %@;\n",covertType,attributeName];

            //制造属性
            proterty=[proterty stringByAppendingString:attriFormatstr];
            
            
        }
        
        
        /*---替换.h-----*/
        // 实体类名
        [templateH replaceOccurrencesOfString:ocEnityName
                                   withString:enityName
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateH.length)];
        
        // 时间
        [templateH replaceOccurrencesOfString:ocDate
                                   withString:dateStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateH.length)];
        
        // property
        [templateH replaceOccurrencesOfString:VariableDeclare
                                   withString:proterty
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateH.length)];
        
        
        
        
        /*---替换.m-----*/
        [templateM replaceOccurrencesOfString:ocEnityName
                                   withString:enityName
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateM.length)];
        
        [templateM replaceOccurrencesOfString:ocDate
                                   withString:dateStr
                                      options:NSCaseInsensitiveSearch
                                        range:NSMakeRange(0, templateM.length)];
        

        
        
        
        NSString * hfileName =[NSString stringWithFormat:@"%@.h",enityName];
        NSString * mfileName =[NSString stringWithFormat:@"%@.cpp",enityName];
        
        //导出文件
        
        NSError * error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        /***导出.h***/
        NSString * filepath=[path stringByAppendingPathComponent:hfileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * url=[NSURL URLWithString:filepath];
        
        //如果文件夹存在
        if ([fileManager fileExistsAtPath:[url path]] ) {
            [fileManager removeItemAtPath:[url path] error:&error];
            
        }
        
        [templateH writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];
        
        /***导出.cpp***/
        filepath=[path stringByAppendingPathComponent:mfileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        url=[NSURL URLWithString:filepath];
        
        
        //如果文件夹存在
        if ([fileManager fileExistsAtPath:[url path]] ) {
            [fileManager removeItemAtPath:[url path] error:&error];
            
        }
        
        //        [templateM writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];
        [templateM writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];
        
        debugLog(@"url: \n :%@ error:%@",[url path],error.description);
        
    }


}


+(void)exportToPlist:(NSArray*)datasource folderPath:(NSString*)path  dbPath:(NSString*)dbpath{

    for (TableEnity * tbenity in datasource) {
        
        
        if (tbenity.isSelected==NO) {
            continue;
        }
        
        
        //实体类的名字
        NSString * enityName=tbenity.enityName ;
        NSArray * attriarr=tbenity.attributes;
        
        //获取需要转换的key
        NSMutableArray * arr=[NSMutableArray array];
        
        for (AttributeEnity * attri in attriarr) {
            if (attri.isSelected==NO) {
                continue;
            }

            NSString * attributeName=attri.attributeName;//属性名字
            [arr addObject:attributeName];
            
            
            
        }
        
        debugLog(@"begin");
        //获取data的arr
        NSArray * dataArr= [HSqlManager getDataWithKeys:arr tableName:enityName dbPath:dbpath];
        
        /*---.plist----*/

        NSString * plistfileName =[NSString stringWithFormat:@"%@.plist",enityName];

        //导出文件
        
        /***导出.plist***/
        NSString * filepath=[path stringByAppendingPathComponent:plistfileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * url=[NSURL URLWithString:filepath];
        
        [dataArr writeToFile:[url path] atomically:YES];
        debugLog(@"end ");
        //debugLog(@"dataArr:%@ \n url: \n :%@ result:%d",dataArr,[url path],result);
        
    }


}




+(void)exportToJson:(NSArray*)datasource folderPath:(NSString*)path dbPath:(NSString*)dbpath{

    
    for (TableEnity * tbenity in datasource) {
        
        
        if (tbenity.isSelected==NO) {
            continue;
        }
        
        
        //实体类的名字
        NSString * enityName=tbenity.enityName ;
        NSArray * attriarr=tbenity.attributes;
        
        //获取需要转换的key
        NSMutableArray * arr=[NSMutableArray array];
        
        for (AttributeEnity * attri in attriarr) {
            if (attri.isSelected==NO) {
                continue;
            }
            
            NSString * attributeName=attri.attributeName;//属性名字
            [arr addObject:attributeName];
            
            
            
        }
        
        debugLog(@"begin");
        //获取data的arr
        NSError * error;
        NSArray * dataArr= [HSqlManager getDataWithKeys:arr tableName:enityName dbPath:dbpath];
        
        NSData * jsonData=[NSJSONSerialization dataWithJSONObject:dataArr options:NSJSONWritingPrettyPrinted error:&error];
        NSString * jsonStr=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        /*---.json----*/
        
        NSString * jsonfileName =[NSString stringWithFormat:@"%@.json",enityName];
        
        //导出文件
        
        /***导出.json***/
        NSString * filepath=[path stringByAppendingPathComponent:jsonfileName];
        filepath=[filepath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * url=[NSURL URLWithString:filepath];
        
        [jsonStr writeToFile:[url path] atomically:YES encoding:NSUTF8StringEncoding error:&error];
        debugLog(@"end ");
       
        
    }



}


@end
